package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.SysUser;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    @Reference
    UserService service ;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @RequestMapping("/loginSuccess")
    public String loginSuccess(){
        return "redirect:http://localhost:83/pages/main.html";
    }

    @RequestMapping("/loginFail")
    public String loginFail(){
        return "redirect:http://localhost:83/login.html?param=loginFail";
    }

    @ResponseBody
    @RequestMapping("/findUsername")
    public Result findUsername(){
        try {
            //获取安全框架的上下文对象(全局对象)(包含了用户信息)
            SecurityContext context = SecurityContextHolder.getContext();
            Object o = context.getAuthentication().getPrincipal();
            User user =(User)o;
            String username = user.getUsername();
            return new Result(true,MessageConst.GET_USERNAME_SUCCESS,username);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.GET_USERNAME_FAIL);
        }

    }

    @RequestMapping("/findMenuByUserId")
    @ResponseBody
    public Result findMenuByUserId() {
        try {
            //获取安全框架的上下文对象
            SecurityContext context = SecurityContextHolder.getContext();
            //获取认证对象
            Authentication authentication = context.getAuthentication();
            //获取用户对象
            Object principal = authentication.getPrincipal();
            User user = (User) principal;
            String username = user.getUsername();
            Integer userId = service.findIdByUsername(username);
//            //根据userid查menu
            List<Map<String,Object>> menuList = service.showMenuByUserId(userId);
//            return new Result(true,MessageConst.GET_USERNAME_SUCCESS,userId);
            return new Result(true, MessageConst.GET_MENU_SUCCESS, menuList);
        } catch (Exception e) {
//            e.printStackTrace();
//            return new Result(false,MessageConst.GET_USERNAME_FAIL);
            return new Result(false, MessageConst.GET_MENU_FAIL);

        }
    }


    @RequestMapping("/findPage")
    @ResponseBody
    @PreAuthorize("hasAuthority('USER_QUERY')")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){

        PageResult pageResult=service.pageQuery(queryPageBean.getCurrentPage(),
                queryPageBean.getPageSize(),
                queryPageBean.getQueryString());

        return pageResult;
    }

    @RequestMapping("/add")
    @ResponseBody
    @PreAuthorize("hasAuthority('USER_ADD')")
    public Result add(@RequestBody SysUser user, Integer[] roles){
        try {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            service.add(user,roles);
            return new Result(true, MessageConstant.ADD_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_USER_FAIL);
        }
    }

    @RequestMapping("/delete")
    @ResponseBody
    @PreAuthorize("hasAuthority('USER_DELETE')")
    public Result delete(Integer id){
        try {
            service.deleteById(id);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return new Result(false,e.getMessage());
        }catch(Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.DELETE_USER_FAIL);
        }
        return new Result(true,MessageConstant.DELETE_USER_SUCCESS);
    }

    @RequestMapping("/findById")
    @ResponseBody
    @PreAuthorize("hasAuthority('USER_QUERY')")
    public Result findById(Integer id){
        try {
            SysUser user=service.findById(id);
            return new Result(true,MessageConstant.QUERY_USER_SUCCESS,user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_USER_FAIL);
        }

    }

    @RequestMapping("/edit")
    @ResponseBody
    @PreAuthorize("hasAuthority('USER_EDIT')")
    public Result edit(@RequestBody SysUser user, Integer[] roles){
        try {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            service.edit(user,roles);
            return new Result(true,MessageConstant.EDIT_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.EDIT_USER_FAIL);
        }
    }


}
